#include "LinearFilterAction.h"
#include <QImage>
#include "Layer.h"
#include "Work.h"

LinearFilterAction::LinearFilterAction () : AbstractAction (), 
		_core (QSize (1, 1)), _pFilter (NULL)
{
	_core (0, 0) = 1.0f;
}

void LinearFilterAction::updatePreview (QRect viewport)
{
	if (_pFilter == NULL)
		return;

	Ptr< Layer > pCurLayer = __pTargetWork->getDoc ()->getCurrentLayer ();
	
	bool isPreview = true;
	if (viewport.isEmpty ()) {
		isPreview = false;
		viewport = pCurLayer->getRegion ();
	}

	QRect updateRegion = viewport & pCurLayer->getRegion ();

	QPoint oSrcImg = pCurLayer->getRegion ().topLeft ();
	QPoint oViewport = viewport.topLeft ();
	QPoint oUpdate = updateRegion.topLeft ();

	QRect processRegion = updateRegion;
	processRegion.translate (-oSrcImg);

	Ptr< QImage > pProcessSrc = new QImage (pCurLayer->getImage ()
			->copy (processRegion));
	Ptr< QImage > pProcessResult = _pFilter->process (pProcessSrc);

	if (isPreview)
		pCurLayer->setPreviewImage (pProcessResult);
	else
		pCurLayer->setImage (pProcessResult);
}

void LinearFilterAction::handleStartEvent ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->openPreview ();
}

void LinearFilterAction::rejectAction ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}

void LinearFilterAction::applyAction ()
{
	updatePreview (QRect ());
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}

void LinearFilterAction::setFilterMethod (Ptr< FilterBase > pFilter)
{
	_pFilter = pFilter;	
}
